import TodoHeader from './components/TodoHeader'
import TodoMain from './components/TodoMain'
import TodoFooter from './components/TodoFooter'
import React,{ useState,useEffect } from 'react'

import './styles/base.css'
import './styles/index.css'

// const initcontent = [
//   {id:'1',content:'抽烟',finish:false},
//   {id:'2',content:'喝酒',finish:true},
//   {id:'3',content:'烫头',finish:false}
// ]
export const MyContext = React.createContext()

const App = () => {
  const [itemList,setItemList] = useState(()=>{
    return JSON.parse(localStorage.getItem('toduinitcontent'))
  })

  useEffect(() => {
    localStorage.setItem('toduinitcontent',JSON.stringify(itemList))
  }, [itemList])

  const cgItemFinish = (id) => { //修改计划状态
    setItemList(itemList.map((item)=>{
      if(item.id === id) {
        return {
          ...item,
          finish: !item.finish
        }
      } else {
        return item
      }
    }))
  }

  const addItem = (name) => {// 添加计划
    setItemList([
      {id:Date.now(),content:name,finish:false},
      ...itemList
    ])
  }

  const delItem = (id) =>{ // 删除计划
    setItemList(itemList.filter((item) => item.id !== id))
  }

  const cgItem = ({id,content}) => { // 修改计划
    setItemList(itemList.map((item) => {
      if(item.id === id) {
        return {
          ...item,
          content
        }
      } else {
        return item
      }
    } ))
  }

  const [tabtype,setTabType] = useState('All') // Tab 栏状态

  const clearItem = () => { // 清除已完成的计划
    setItemList(itemList.filter((item) => item.finish !== true))
  }

  const cgAllItemFinish = (type) => {
    setItemList(itemList.map((item)=>{
      return {
        ...item,
        finish: type
      }
    }))
  }

  return (
    <MyContext.Provider value={{cgItemFinish,delItem,cgItem}}>
      <section className="todoapp">
        <TodoHeader addItem={addItem}/>
        <TodoMain itemList={itemList} tabtype={tabtype} cgAllItemFinish={cgAllItemFinish}/>
        <TodoFooter itemList={itemList} tabtype={tabtype} setTabType={setTabType} clearItem={clearItem}/>
      </section>
    </MyContext.Provider>
  )
}

export default App
